#include "stm32f1xx_hal.h"
#include "DAC8552.h"
#include "spi.h"
#include "HAL_OLED.h"
#include <stdio.h>

void DAC8552_Init(void)
{
	__HAL_RCC_GPIOA_CLK_ENABLE();
	
	
	GPIO_InitTypeDef GPIO_InitStruct = {0}; 

	GPIO_InitStruct.Pin = CS_PIN|SCLK_PIN|DIN_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	HAL_GPIO_Init(GPIOx, &GPIO_InitStruct);
	
	SCLK_1;
	CS_1;
}

void DAC8552_WriteValueBySoftWare(uint32_t Data)
{
	uint16_t i = 0;
	Data<<=8;
	
	SCLK_0;
	CS_0;
	SCLK_1;
	
	for(i = 0; i<24;i++)
	{
		if(Data & 0x80000000)
		{
			DIN_1;
			
		}
		else 
		{
			DIN_0;
		}
		SCLK_0;
		
		Data <<= 1;
		SCLK_1;
	}
	CS_1;
	
}


uint32_t DAC8552_VoltageToData(float Vref, float Voltage)
{
	uint32_t Data = 0;
	
	Data = (uint32_t)(65535 * Voltage / Vref);
	if(Data>65535)
	{
		Data = 65535;
		
	}
	
	Data &= 0x00ffff;
	return Data;
	
}

void DAC8552_WriteB(float Voltage)
{
	uint32_t Data = 0;
	Data = DAC8552_VoltageToData(DAC8552_Vref, Voltage);
	Data = DAC8552_ChannelB|Data;
	
	DAC8552_WriteValueBySoftWare(Data);
}

void DAC8552_WriteA(float Voltage)
{
	uint32_t Data = 0;
	Data = DAC8552_VoltageToData(DAC8552_Vref, Voltage);
	Data = DAC8552_ChannelA|Data;
	
	DAC8552_WriteValueBySoftWare(Data);
}

